const movies = [{
    video: 'http://vt1.doubanio.com/201908231123/0a5e3d8259f2de3e7670eff4110fab35/view/movie/M/302190491.mp4',
    doubanID: '26739551/',
    cover: 'https://img1.doubanio.com/img/trailer/medium/2493603388.jpg?',
    poster: 'https://img3.doubanio.com/view/photo/l_ratio_poster/public/p2563801472.jpg'
}]

const qiniu = require("qiniu")

const nanoid = require("nanoid")

const config = require("../config")

const bucket = config.qiniu.bucket
const mac = new qiniu.auth.digest.Mac(config.qiniu.AK, config.qiniu.SK)

const cfg = new qiniu.conf.Config()

const client = new qiniu.rs.BucketManager(mac, cfg)

const uploadToQiniu = async (url, key) => {
    return new Promise((resolve, reject) => {
        client.fetch(url, bucket, key, (err, ret, info) => {
            if (err) {
                reject(err)
            } else {
                if (info.statusCode === 200) {
                    resolve({ key })
                } else {
                    reject(info)
                }
            }
        })
    })
}

    ; (async () => {
        let movies = [{
            video: 'http://vt1.doubanio.com/201908231123/0a5e3d8259f2de3e7670eff4110fab35/view/movie/M/302190491.mp4',
            doubanID: '26739551/',
            cover: 'https://img1.doubanio.com/img/trailer/medium/2493603388.jpg?',
            poster: 'https://img3.doubanio.com/view/photo/l_ratio_poster/public/p2563801472.jpg'
        }]

        movies.map(async movie => {
            if (movie.video && !movie.key) {
                try {
                    console.log("开始传video")
                    let videoData = await uploadToQiniu(movie.video, nanoid() + ".mp4")
                    console.log("开始传cover")
                    let coverData = await uploadToQiniu(movie.cover, nanoid() + '.jpg')
                    console.log("开始传poster")
                    let posterData = await uploadToQiniu(movie.poster, nanoid() + ".jpg")

                    if (videoData.key) {
                        movie.videoKey = videoData.key
                    }
                    if (coverData.key) {
                        movie.coverKey = coverData.key
                    }
                    if (posterData.key) {
                        movie.coverKey = posterData.key
                    }
                    console.log(movie)
                } catch (err) {
                    console.log(err)
                }
            }
        })
    })()